package intranet.client;

import java.util.HashMap;
import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.VerticalPanel;


/**
 * @author AHMIM Ahmed && BAKHTI Yassine
 *
 */



public class ShareTab extends VerticalPanel {
	
	
	String prevpass = null;
	Grid grid = new Grid(4,4);
	ListBox list1 = new ListBox(true);
	ListBox list2 = new ListBox(true);
	ListBox list3 = new ListBox(true);
	VerticalPanel hpanel = new VerticalPanel();
	PushButton add,sup,supprimer;
	Button valider;
	String requet;
	Vector<String> v1,v2; 
	Session session;
	
	

	
	DataBaseServiceAsync dataBaseService = GWT.create(DataBaseService.class);
	
	/**
	 * Cette méthode représente le constructeur de la classe ShareTab 
	 * @param seesion c'est la session courante 
	 * 
	 */	
	
	ShareTab(final Session session){
	/**
	 * This is the entry point method.
	 */

	
	

		this.session=session ;
		
		
		
		VerticalPanel mainpanel = new VerticalPanel();
		
			grid.setCellSpacing(10);
			//list1.setSize("100px", "150px");
			list1.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
			
			
			list1.setVisibleItemCount(5);
			//list2.setSize("100px", "150px");
			list2.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
			list2.setVisibleItemCount(5);
			//list3.setSize("100px", "150px");
			list3.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
			list3.setVisibleItemCount(5);
			grid.setWidget(0, 0, list1);		
			grid.setWidget(0, 1, list2);
			v1=new Vector<String>();
			v2=new Vector<String>();
			add=new PushButton(new Image("add.png"));
			//add.setSize("22px", "22px");
			add.setSize(Window.getClientWidth()*16/20*1/38+"px", Window.getClientHeight()*9/10*3/50+"px");
			sup=new PushButton(new Image("delete.png"));
			//sup.setSize("22px","22px");
			sup.setSize(Window.getClientWidth()*16/20*1/38+"px", Window.getClientHeight()*9/10*3/50+"px");
			supprimer=new PushButton(new Image("delete.png"));
			//supprimer.setSize("30px","30px");
			supprimer.setSize(Window.getClientWidth()*16/20*1/38+"px", Window.getClientHeight()*9/10*3/50+"px");
			
			hpanel.add(add);
			hpanel.add(sup);
			
			grid.setWidget(0, 2, hpanel);
			grid.setWidget(0, 3, list3);
			
			valider = new Button("Valider");
			valider.setSize("100px","30px");
			
			
			grid.setWidget(1,0, supprimer);
			grid.setWidget(1,3, valider);
			
			mainpanel.add(grid);
	
		getdata();		
		this.add(mainpanel);
		
//Ajouter un événement associé au click sur le bouton sup afin de supprimer un enseignant du partage de ducument	
		
		sup.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
             if (list3.getSelectedIndex()!=-1)
		    	{
            	 
            	list2.addItem(list3.getItemText(list3.getSelectedIndex()));
		    	v1.add(v2.elementAt(list3.getSelectedIndex())); 
		    	v2.removeElementAt(list3.getSelectedIndex());
		    	list3.removeItem(list3.getSelectedIndex());	
		    	}
		    
		    }
		  });

//Ajouter un événement associé au click sur le bouton add afin de d'ajouter un enseignant au partage du document
		add.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{		
		    			    			    			    	
				if (list2.getSelectedIndex()!=-1)
		    	{
				list3.addItem(list2.getItemText(list2.getSelectedIndex()));
		    	v2.add(v1.elementAt((list2.getSelectedIndex())));
		    	v1.removeElementAt(list2.getSelectedIndex());
		    	list2.removeItem(list2.getSelectedIndex());
		        }
				
		    }
		  });
			

//Ajouter un événement associé au click sur un item de la liste des documents afin  d'ajouter a la liste2 tout 
		// les enseignants auxquels on n'a pas partager le document selectionné		
	  list1.addChangeHandler( new ChangeHandler()
	  {
		  public void onChange(ChangeEvent event)
		  {
			  list2.clear();
			  list3.clear();
			  v1.clear();
			  v2.clear();
//---------------------------------------------------------------------------------------------------		
String reqeacher ="select d.document_name,d.document_id from teacher_document as dt,document as d where teacher_login='"+
session.get("teacher_login")+ "' and dt.document_id=d.document_id";
				
				
				dataBaseService.select(reqeacher, new  AsyncCallback<HashMap<String,String[]>>()
									
									{
							
								public void onSuccess( HashMap<String, String[]> result )
									{
			  
			  
//--------------------------------------------------------------------------------------------------			  
			  

String requet1="select teacher.teacher_login,teacher.teacher_name,teacher.teacher_firstname from teacher ," +"teacher_document where teacher.teacher_login not in (select teacher_login from teacher_document where document_id = '"+result.get("document_id")[list1.getSelectedIndex()]+"' ) group by teacher.teacher_name,teacher.teacher_login,teacher.teacher_firstname";	       

dataBaseService.select(requet1, new  AsyncCallback<HashMap<String,String[]>>()
		
		{
	

	public void onSuccess( HashMap<String, String[]> result )
		{ 
  	for (int i=0;i<result.get("teacher_login").length;i++)
  	{	



  		
  	   list2.addItem(result.get("teacher_firstname")[i].charAt(0)+". "+result.get("teacher_name")[i]);

  	   v1.add(result.get("teacher_login")[i]);
  	   
  	}
		}
	
			public void onFailure( Throwable caught ) {
				
				Window.alert("erreur bado");
				}

		
		
		});	
									
									
									
									
									}
								
								public void onFailure( Throwable caught ) {
									
									Window.alert("erreur bado");
									}

							
							
							});	
//------------------------------------------------------------------------------------------------------
	            }
	    }); 
	  
//Ajouter un événement associé au click sur le bouton valider afin de valider le partage de document	  
valider.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{	        
					    
    String requet4="select d.document_name,dt.document_id from teacher_document as dt,document as d where teacher_login='"
		+session.get("teacher_login")+"' and dt.document_id=d.document_id";
					    
	dataBaseService.select(requet4, new AsyncCallback<HashMap<String,String[]>>() {
	
public void onSuccess(HashMap<String, String[]> result) {
											   											
												
	for(int i=0;i<v2.size();i++)
	{  
		add_teacher_doc(v2.elementAt(i),result.get("document_id")[0]);
	}			
													
list3.clear();
list1.clear();
list2.clear();
list3.clear();
v1.clear();
v2.clear();
getdata();															

}
												
public void onFailure(Throwable caught) 
{
																																							
}});	
												
}
											
});		
					   
	        	
	        
	      
//Ajouter un événement associé au click sur le bouton supprimer afin de supprimer le document 
	  supprimer.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
		        	
 requet ="select d.document_name,dt.document_id from teacher_document as dt,document as d where teacher_login='"
					+session.get("teacher_login")+"' and dt.document_id=d.document_id";
 
		        	dataBaseService.select(requet, new AsyncCallback<HashMap<String,String[]>>() {
		        		
		        		public void onSuccess(HashMap<String, String[]> result) {
		        			
		        			if(list1.getSelectedIndex()!=-1)
		        			{		        	       	
	String requet1 ="DELETE FROM teacher_document where document_id='"+result.get("document_id")[list1.getSelectedIndex()]+"' and teacher_login='"
		  + session.get("teacher_login")+"'";
		      
		      dataBaseService.delete(requet1, new AsyncCallback<Integer>()
							{
								public void onSuccess(Integer result)
								{
									if (result>0)
									{
										
										list1.clear();
										getdata();
									    
									}
								}
								
								public void onFailure(Throwable caught)
								{
									
								}
							});		
		        			}
		        		}
		        		
		        		public void onFailure(Throwable caught) {
		        	// TODO Auto-generated method stub	
		        		Window.alert("cassé");
		        		}
		        	});
		      
		   
				} });
	  
	  
		   }
		
	/**
	 * Cette méthode sert à ajouter la liste des documents dans la premiére liste  
	 */	
	
	protected void getdata() {
		
	
	String reqeacher ="select d.document_name from teacher_document as dt,document as d where teacher_login='"
		+session.get("teacher_login")+"' and dt.document_id=d.document_id";
					
				
	dataBaseService.select(reqeacher, new  AsyncCallback<HashMap<String,String[]>>()
						
						{
				
					public void onSuccess( HashMap<String, String[]> result )
						{
				  	for (int i=0;i<result.get("document_name").length;i++)
						list1.addItem(result.get("document_name")[i]);
						
						}
					
							public void onFailure( Throwable caught ) {
								
								Window.alert("erreur bado");
								}

						
						
						});	
			}
	
	/**
	 * Cette méthode sert à inserer un enregistrement dans la table teacher_document
	 * @param  user_id identifiant de l'utilisateur , doc identifiant du document 
	 */	

	public void add_teacher_doc(String user_id,String doc)
	{
		String requet3;
		requet3 ="insert into teacher_document (document_id ,teacher_login ) values('"+doc+"','"+user_id+"')";
		
			   
			      dataBaseService.insert(requet3, new AsyncCallback<Integer>()
								{
									public void onSuccess(Integer result)
									{
										
									}
									
									public void onFailure(Throwable caught)
									{
										
									}
								});		


	}	
	
	
	/**
	 * Cette méthode sert à redimensionner la taille de la table ShareTab en fonction de la taille de la page
	 */
	
	public void onResize()
	{
		list1.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
		list2.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
		list3.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
		add.setSize(Window.getClientWidth()*16/20*1/38+"px", Window.getClientHeight()*9/10*3/50+"px");
		sup.setSize(Window.getClientWidth()*16/20*1/38+"px", Window.getClientHeight()*9/10*3/50+"px");
		supprimer.setSize(Window.getClientWidth()*16/20*1/38+"px", Window.getClientHeight()*9/10*3/50+"px");
		
	}
	
	
}
